package com.graduate.examapp.view.fragment

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.graduate.examapp.R
import com.graduate.examapp.adapter.TeacherRecycleViewAdapter
import com.graduate.examapp.databinding.FragmentTeacherBinding
import com.graduate.examapp.entity.UserInfoFactory
import com.graduate.examapp.view.customview.CustomTeacherAddDialog
import com.graduate.examapp.viewmodel.TeacherViewModel
import com.z.fileselectorlib.FileSelectorSettings
import com.z.fileselectorlib.FileSelectorTheme
import com.z.fileselectorlib.Objects.FileInfo
import me.rosuh.filepicker.config.FilePickerManager
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.RequestBody
import java.io.File


class TeacherFragment : Fragment() {
    private var theme: FileSelectorTheme? = null
    val settings = FileSelectorSettings()

    private var binding: FragmentTeacherBinding? = null

    val teacherViewModel: TeacherViewModel by lazy {
        val model = ViewModelProvider(this)[TeacherViewModel::class.java]
        model
    }
    private var recyclerView: RecyclerView? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.i("TeacherFragment", "create")
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_teacher,
            container,
            false
        )
        //用户基础信息
        init()
        return binding?.root
    }

    override fun onResume() {
        super.onResume()
        Log.d("TeacherFragment", "onResume()")
        request()
    }

    private fun init() {
        recyclerView = binding?.root?.findViewById<RecyclerView>(R.id.teacher_recycle)
        recyclerView?.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        val teacherRecycleViewAdapter = TeacherRecycleViewAdapter(teacherViewModel, requireContext())
        recyclerView?.adapter = teacherRecycleViewAdapter

        teacherViewModel.teacherLiveData.observe(requireActivity()) {
            it?.let {
                teacherRecycleViewAdapter.dataSource = it
                teacherRecycleViewAdapter.notifyDataSetChanged()
                Log.d("DataFragment", teacherRecycleViewAdapter.itemCount.toString())
            }
        }
        // 监听删除结果显示 操作提示
        teacherViewModel.teacherDelMsgLiveData.observe(requireActivity()) {
            Toast.makeText(requireContext(), it, Toast.LENGTH_SHORT).show()
        }
        // 点击添加单个教师
        binding?.root?.findViewById<FloatingActionButton>(R.id.floating_addteacher_btn)
            ?.setOnClickListener {
                CustomTeacherAddDialog(requireContext()) {
                    val connectivityManager = this.context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                    val info: NetworkInfo? = connectivityManager.getActiveNetworkInfo()
                    if (info != null && info.isAvailable()) {
                        val name = info.getTypeName()
                        teacherViewModel.addTeacher(it)
                    } else {
                        Toast.makeText(this.context, "网络连接不可用", Toast.LENGTH_LONG).show()
                    }
                }.show()
            }

        theme = FileSelectorTheme()
        theme?.setTopToolBarTitleColor("#000000")
            ?.setThemeColor("#FFFFFF")
            ?.setTopToolBarBackIcon(R.drawable.icon_return_black_20)


        binding?.root?.findViewById<FloatingActionButton>(R.id.floatting_batchaddteacher_btn)
            ?.setOnClickListener {

                settings.setRootPath(FileSelectorSettings.getSystemRootPath()) //起始路径
                    .setTheme(theme)
                    .setMaxFileSelect(1) //最大文件选择数
                    .setTitle("请选择Excel格式教师文件")
                    .setFileTypesToSelect(FileInfo.FileType.File) //可选择文件类型
                    .show(requireActivity()) //显示
            }
    }



    private fun request() {
        val insName = UserInfoFactory.loginData?.insName
        if (insName != null) {
            val connectivityManager = this.context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val info: NetworkInfo? = connectivityManager.getActiveNetworkInfo()
            if (info != null && info.isAvailable()) {
                val name = info.getTypeName()
                teacherViewModel.getTeacherList(insName)
            } else {
                Toast.makeText(this.context, "网络连接不可用", Toast.LENGTH_LONG).show()
            }
        }
    }

}